import React, {useEffect, useState} from 'react';
import {X} from 'lucide-react';

interface UserFormData {
    id?: string;
    name: string;
    gender: string;
    birthday: string;
    phone: string;
    region: string;
    team: string;
    department: string;
    position: string;
    role: 'user' | 'admin';
    password: string;
    areaId: string;
    teamId: string;
    departId: string;
    realname: string;
    type: string;
    roleId: string;
}

interface Region {
    id: string;
    name: string;
    teams: Team[];
}

interface Team {
    id: string;
    name: string;
    departments: Department[];
}

interface Department {
    id: number;
    name: string;
}


const initialFormData: UserFormData = {
    name: '',
    gender: '0',
    birthday: '',
    phone: '',
    region: '',
    team: '',
    department: '',
    position: '',
    role: 'user',
    password: '',
    areaId: '',
    teamId: '',
    departId: '',
    realname: '',
    type: '',
    roleId: '',
};

export default function UserFormModal({
                                          mode,
                                          userData,
                                          regions,
                                          roles,
                                          onClose,
                                          onSave
                                      }: any) {
    const [formData, setFormData] = useState<UserFormData>(initialFormData);
    const [selectedRegion, setSelectedRegion] = useState<string>('');
    const [selectedRegionData, setSelectedRegionData] = useState<Region>(regions.find(r => r.id == userData?.areaId));
    const [selectedTeam, setSelectedTeam] = useState<string>('');
    const [selectedTeamData, setSelectedTeamData] = useState<Team>(selectedRegionData?.teams.find(t => t.id == userData?.teamId));
    const [errors, setErrors] = useState<Partial<Record<keyof UserFormData, string>>>({});


    useEffect(() => {
        if (mode === 'edit' && userData) {
            setFormData({...initialFormData, ...userData, gender: userData.sex});
            setSelectedRegion(userData.areaId);
            setSelectedTeam(userData.teamId);
        }
        console.log('UserFormModal', userData, formData)
    }, []);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
        const {name, value} = e.target;
        console.log('handleChange', name, value)
        setFormData(prev => ({...prev, [name]: value}));
        setErrors(prev => ({...prev, [name]: ''}));
    };

    const handleRegionChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const region = e.target.value;
        setSelectedRegion(region);
        setSelectedRegionData(regions.find(r => r.id == region))
        setSelectedTeam('');
        setFormData(prev => ({
            ...prev,
            areaId: region,
            teamId: '',
            departId: ''
        }));
        console.log('handleRegionChange')
    };

    const handleTeamChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const team = e.target.value;
        setSelectedTeam(team);
        setSelectedTeamData(selectedRegionData?.teams.find(t => t.id == team));
        setFormData(prev => ({
            ...prev,
            teamId: team,
            departId: ''
        }));
        console.log('handleTeamChange')
    };

    const validateForm = () => {
        const newErrors: Partial<Record<keyof UserFormData, string>> = {};

        if (!formData.realname.trim()) {
            newErrors.name = '姓名不能为空';
        }

        if (!formData.phone.trim()) {
            newErrors.phone = '手机号不能为空';
        } else if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
            newErrors.phone = '请输入有效的手机号';
        }

        if (mode === 'add' && !formData.password) {
            newErrors.password = '密码不能为空';
        }

        if (!formData.departId) {
            newErrors.department = '请选择所属部门';
        }

        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (validateForm()) {
            onSave(formData);
        }
    };



    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
            <div className="bg-white rounded-lg w-full max-w-2xl mx-4 max-h-[90vh] flex flex-col">
                <div className="flex items-center justify-between p-4 border-b">
                    <h3 className="text-lg font-semibold text-gray-900">
                        {mode === 'add' ? '添加用户' : '编辑用户'}
                    </h3>
                    <button onClick={onClose}>
                        <X className="w-6 h-6 text-gray-500"/>
                    </button>
                </div>

                <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto p-6">
                    <div className="space-y-6">
                        {/* 基本信息 */}
                        <div className="grid grid-cols-2 gap-6">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    姓名 <span className="text-red-500">*</span>
                                </label>
                                <input
                                    type="text"
                                    name="realname"
                                    defaultValue={formData.realname}
                                    onChange={handleChange}
                                    className={`w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                                        errors.name ? 'border-red-500' : 'border-gray-300'
                                    }`}
                                />
                                {errors.name && (
                                    <p className="mt-1 text-sm text-red-500">{errors.name}</p>
                                )}
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    性别
                                </label>
                                <select
                                    name="gender"
                                    defaultValue={userData?.sex}
                                    onChange={handleChange}
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                >
                                    <option value=''>请选择</option>
                                    <option value="0">男</option>
                                    <option value="1">女</option>
                                </select>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    生日
                                </label>
                                <input
                                    type="date"
                                    name="birthday"
                                    defaultValue={formData.birthday ? formData.birthday.substr(0, 10) : null}
                                    onChange={handleChange}
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    手机号 <span className="text-red-500">*</span>
                                </label>
                                <input
                                    type="tel"
                                    name="phone"
                                    defaultValue={formData.phone}
                                    onChange={handleChange}
                                    className={`w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                                        errors.phone ? 'border-red-500' : 'border-gray-300'
                                    }`}
                                />
                                {errors.phone && (
                                    <p className="mt-1 text-sm text-red-500">{errors.phone}</p>
                                )}
                            </div>
                        </div>

                        {/* 组织信息 */}
                        <div className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    所属区域 <span className="text-red-500">*</span>
                                </label>
                                <select
                                    name="areaId"
                                    defaultValue={userData?.areaId}
                                    onChange={handleRegionChange}
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    required
                                >
                                    <option value="">请选择区域</option>
                                    {regions.map(region => (
                                        <option key={region.id} value={region.id}>
                                            {region.name}
                                        </option>
                                    ))}
                                </select>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    所属团队 <span className="text-red-500">*</span>
                                </label>
                                <select
                                    name="teamId"
                                    defaultValue={userData?.teamId}
                                    onChange={handleTeamChange}
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    required
                                    disabled={!selectedRegion}
                                >
                                    <option value="">请选择团队</option>
                                    {selectedRegionData?.teams.map(team => (
                                        <option key={team.id} value={team.id}>
                                            {team.name}
                                        </option>
                                    ))}
                                </select>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    所属部门 <span className="text-red-500">*</span>
                                </label>
                                <select
                                    name="departId"
                                    defaultValue={userData?.departId}
                                    onChange={handleChange}
                                    className={`w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                                        errors.department ? 'border-red-500' : 'border-gray-300'
                                    }`}
                                    required
                                    disabled={!selectedTeam}
                                >
                                    <option value="">请选择部门</option>
                                    {selectedTeamData?.departments.map(dept => (
                                        <option key={dept.id} value={dept.id}>
                                            {dept.name}
                                        </option>
                                    ))}
                                </select>
                                {errors.department && (
                                    <p className="mt-1 text-sm text-red-500">{errors.department}</p>
                                )}
                            </div>
                        </div>

                        {/* 职位和角色 */}
                        <div className="grid grid-cols-2 gap-6">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    职位<span className="text-red-500">*</span>
                                </label>
                                <input
                                    type="text"
                                    name="position"
                                    defaultValue={formData.position}
                                    onChange={handleChange}
                                    required
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    角色权限<span className="text-red-500">*</span>
                                </label>
                                <select
                                    name="roleId"
                                    defaultValue={userData?.roleId}
                                    onChange={handleChange}
                                    required
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                >
                                    <option value="">请选择角色</option>
                                    {roles.map(role => (
                                        <option key={role.id} value={role.id}>
                                            {role.name}
                                        </option>
                                    ))}
                                </select>
                            </div>
                        </div>

                        {/* 密码 */}
                        {mode === 'add' && (
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    密码 <span className="text-red-500">*</span>
                                </label>
                                <input
                                    type="password"
                                    name="password"
                                    value={formData.password}
                                    onChange={handleChange}
                                    className={`w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                                        errors.password ? 'border-red-500' : 'border-gray-300'
                                    }`}
                                />
                                {errors.password && (
                                    <p className="mt-1 text-sm text-red-500">{errors.password}</p>
                                )}
                            </div>
                        )}
                    </div>

                    <div className="flex justify-end space-x-3 mt-6">
                        <button
                            type="button"
                            onClick={onClose}
                            className="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg"
                        >
                            取消
                        </button>
                        <button
                            type="submit"
                            className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                        >
                            确定
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
}